package cn.hchaojie.lucene.query;

import java.io.IOException;

import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.queryparser.classic.MultiFieldQueryParser;
import org.apache.lucene.queryparser.classic.ParseException;
import org.apache.lucene.queryparser.classic.QueryParser;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.TopDocs;
import org.junit.Test;

public class DemoQueryParser {
	@Test
	public void test1() throws ParseException, IOException {
		// queryParser会先对搜索条件进行分词，再搜索
		// 默认搜索域
		QueryParser parser = new QueryParser("name", new StandardAnalyzer());
		
		Query query = parser.parse("+name:apache +lucene");
		
		IndexSearcher indexSearcher = LuceneUtils.getIndexSearcher();
		TopDocs topDocs = indexSearcher.search(query, 10);
		LuceneUtils.printResult(indexSearcher, topDocs);
	}
	
	@Test
	public void test2() throws ParseException, IOException {
		// queryParser会先对搜索条件进行分词，再搜索
		// 默认搜索域
		QueryParser parser = new QueryParser("name", new StandardAnalyzer());
		
		Query query = parser.parse("编程之道");
		
		System.out.println(query);

		IndexSearcher indexSearcher = LuceneUtils.getIndexSearcher();
		TopDocs topDocs = indexSearcher.search(query, 10);
		LuceneUtils.printResult(indexSearcher, topDocs);
	}
	
	// 查询文件名或者文件内容含有apache的documents
	@Test
	public void test3() throws ParseException, IOException {
		// 指定多个默认搜索域
		MultiFieldQueryParser parser = new MultiFieldQueryParser(
				new String[] {"name", "content"}, new StandardAnalyzer());
		
		Query q1 = parser.parse("name:apache content:apache");
		System.out.println(q1);
		Query q2 = parser.parse("apache");
		System.out.println(q2);

		IndexSearcher indexSearcher = LuceneUtils.getIndexSearcher();
		TopDocs topDocs = indexSearcher.search(q1, 10);
		LuceneUtils.printResult(indexSearcher, topDocs);
	}
}
